package logic

import (
	"context"
	"strconv"

	"probe-users/internal/errorx"
	"probe-users/internal/svc"
	"probe-users/internal/utils"
	"probe-users/pb/users"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type CheckUserPermissionLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCheckUserPermissionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CheckUserPermissionLogic {
	return &CheckUserPermissionLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 权限检查
func (l *CheckUserPermissionLogic) CheckUserPermission(in *users.CheckUserPermissionRequest) (*users.CheckUserPermissionResponse, error) {
	// 1. 解析Token
	claims, err := utils.ParseToken(in.Token, l.svcCtx.Config.JWTAuth.AccessSecret)
	if err != nil {
		return nil, errorx.ErrInvalidToken
	}

	// 2. 校验权限
	sub := strconv.FormatInt(claims.RoleId, 10)
	hasPerm, err := l.svcCtx.Enforcer.Enforce(sub, in.Obj, in.Act)
	if err != nil {
		return nil, errors.Wrapf(err, "权限校验失败")
	}

	// 3. 返回结果
	return &users.CheckUserPermissionResponse{HasPermission: hasPerm}, nil
}
